import 'package:get/get.dart';
import 'package:shimo_app/pages/components/hint.dart';

import '../../services/device_service.dart';
import 'calibration_component_state.dart';

/// 校准组件控制器 - 负责设备校准相关的业务逻辑
class CalibrationComponentController extends GetxController {
  final Calibration_componentState state = Calibration_componentState();

  // 校准参数和状态变量
  int selectedCalibrationPipeIndex = 0; // 选中的校准管道索引
  int valveChannel = 10; // 阀门通道数量
  List<double> actureDosageValue = []; // 实际剂量值列表

  // 传感器检测值
  int detectorVal_ml = 0; // 毫升检测值
  int detectorVal_bra = 0; // 臂检测值
  int detectorVal = 0; // 综合检测值
  int emptyDetectValue = 0; // 空容器检测值
  int emptyDetectValue1 = 0; // 空容器检测值1
  int fullDetectValue = 0; // 满容器检测值
  int fullDetectValue1 = 0; // 满容器检测值1
  int fullDetectValue2 = 0; // 满容器检测值2
  int customerDetectValue = 0; // 客户自定义检测值

  // 传感器状态控制
  bool _startGetSensorValue = false; // 是否开始持续获取传感器值

  // 机械臂校准值
  int xarmHomeCalibrationValue = 0; // X轴归位校准值
  int yarmHomeCalibrationValue = 0; // Y轴归位校准值

  // 输入校准值（临时存储）
  int inputXarmHomeValue = 0; // 输入的X轴归位值
  int inputYarmHomeValue = 0; // 输入的Y轴归位值

  // PID参数 - 通道1
  int inputKp11 = 0, inputKi11 = 0, inputKd11 = 0; // 输入PID参数11
  int inputKp12 = 0, inputKi12 = 0, inputKd12 = 0; // 输入PID参数12
  int inputKp13 = 0, inputKi13 = 0, inputKd13 = 0; // 输入PID参数13

  // PID参数 - 通道2
  int inputKp21 = 0, inputKi21 = 0, inputKd21 = 0; // 输入PID参数21
  int inputKp22 = 0, inputKi22 = 0, inputKd22 = 0; // 输入PID参数22
  int inputKp23 = 0, inputKi23 = 0, inputKd23 = 0; // 输入PID参数23

  // 当前PID参数 - 通道1
  int Kp11 = 0, Ki11 = 0, Kd11 = 0; // PID参数11
  int Kp12 = 0, Ki12 = 0, Kd12 = 0; // PID参数12
  int Kp13 = 0, Ki13 = 0, Kd13 = 0; // PID参数13

  // 当前PID参数 - 通道2
  int Kp21 = 0, Ki21 = 0, Kd21 = 0; // PID参数21
  int Kp22 = 0, Ki22 = 0, Kd22 = 0; // PID参数22
  int Kp23 = 0, Ki23 = 0, Kd23 = 0; // PID参数23

  // 通道清洁参数
  int channelCleanDosage = 0; // 通道清洁剂量
  int inputChannelCleanDosage = 0; // 输入的通道清洁剂量
  int selectedSpeedLevel = 0; // 选中的速度等级

  // 加热器校准参数
  List<int> heaterCalibrations = [500, 1200, 1700, 2400]; // 加热器1校准值
  List<int> heaterCalibrations1 = [500, 1200, 1700, 2400]; // 加热器2校准值
  List<int> heaterTargets = [50, 120, 170, 240]; // 加热器1目标温度
  List<int> heaterTargets1 = [50, 120, 170, 240]; // 加热器2目标温度
  List<int> inputHeaterCalibrations = [0, 0, 0, 0]; // 输入的加热器1校准值
  List<int> inputHeaterCalibrations1 = [0, 0, 0, 0]; // 输入的加热器2校准值

  // 设备服务实例
  final deviceService = Get.find<DeviceService>();

  // 加热状态
  bool heating = false; // 加热器1状态
  bool heating1 = false; // 加热器2状态
  int heatingNodule = 0; // 加热节点

  @override
  void onInit() {
    // 初始化剂量值列表
    actureDosageValue = List.generate(valveChannel, (index) => 0);

    // 从设备服务加载所有校准参数
    xarmHomeCalibrationValue = deviceService.getCalibrationValue("x home");
    yarmHomeCalibrationValue = deviceService.getCalibrationValue("y home");
    customerDetectValue = deviceService.getCalibrationValue("cust l");

    // 加载PID参数 - 通道1
    Kp11 = deviceService.getCalibrationValue("Kp11");
    Ki11 = deviceService.getCalibrationValue("Ki11");
    Kd11 = deviceService.getCalibrationValue("Kd11");
    Kp12 = deviceService.getCalibrationValue("Kp12");
    Ki12 = deviceService.getCalibrationValue("Ki12");
    Kd12 = deviceService.getCalibrationValue("Kd12");
    Kp13 = deviceService.getCalibrationValue("Kp13");
    Ki13 = deviceService.getCalibrationValue("Ki13");
    Kd13 = deviceService.getCalibrationValue("Kd13");

    // 加载PID参数 - 通道2
    Kp21 = deviceService.getCalibrationValue("Kp21");
    Ki21 = deviceService.getCalibrationValue("Ki21");
    Kd21 = deviceService.getCalibrationValue("Kd21");
    Kp22 = deviceService.getCalibrationValue("Kp22");
    Ki22 = deviceService.getCalibrationValue("Ki22");
    Kd22 = deviceService.getCalibrationValue("Kd22");
    Kp23 = deviceService.getCalibrationValue("Kp23");
    Ki23 = deviceService.getCalibrationValue("Ki23");
    Kd23 = deviceService.getCalibrationValue("Kd23");

    // 加载通道清洁参数
    channelCleanDosage = deviceService.getCalibrationValue("cln do");

    // 加载加热器校准参数
    heaterCalibrations[0] = deviceService.getCalibrationValue("h1 cal1");
    heaterCalibrations[1] = deviceService.getCalibrationValue("h1 cal2");
    heaterCalibrations[2] = deviceService.getCalibrationValue("h1 cal3");
    heaterCalibrations[3] = deviceService.getCalibrationValue("h1 cal4");
    heaterCalibrations1[0] = deviceService.getCalibrationValue("h2 cal1");
    heaterCalibrations1[1] = deviceService.getCalibrationValue("h2 cal2");
    heaterCalibrations1[2] = deviceService.getCalibrationValue("h2 cal3");
    heaterCalibrations1[3] = deviceService.getCalibrationValue("h2 cal4");

    // 加载传感器检测值
    emptyDetectValue = deviceService.getCalibrationValue("empty l");
    emptyDetectValue1 = deviceService.getCalibrationValue("empty 2");
    fullDetectValue = deviceService.getCalibrationValue("full 1");
    fullDetectValue1 = deviceService.getCalibrationValue("full 2");
    fullDetectValue2 = deviceService.getCalibrationValue("full 3");

    update();
    super.onInit();
  }

  /// 开启加热器1
  /// [target] 目标温度
  Future<bool> heatOn(int target) async {
    heating = true;
    update();

    // 执行加热动作
    final r = await deviceService.componentAction(
        deviceService.heaterId, deviceService.heatOn, target);

    if (!r) {
      heating = false;
      update();
    }
    return r;
  }

  /// 开启加热器2
  /// [target] 目标温度
  Future<bool> heatOn1(int target) async {
    heating1 = true;
    update();

    final r = await deviceService.componentAction(
        deviceService.heaterId, deviceService.heatOn1, target);

    if (!r) {
      heating1 = false;
      update();
    }
    return r;
  }

  /// 关闭加热器1
  Future<bool> heatOff() async {
    heating = false;
    update();
    return deviceService.componentAction(
        deviceService.heaterId, deviceService.heatOff, 0);
  }

  /// 关闭加热器2
  Future<bool> heatOff1() async {
    heating1 = false;
    update();
    return deviceService.componentAction(
        deviceService.heaterId, deviceService.heatOff1, 0);
  }

  /// 设置加热器1校准值
  /// [id] 校准点索引 (0-3)
  /// [value] 校准值
  Future<void> setHeaterCalibration(int id, int value) async {
    heaterCalibrations[id] = value;
    update();

    // 保存到设备服务
    final result =
        await deviceService.saveCalibrationValue("h1 cal${id + 1}", value);

    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
  }

  /// 设置加热器2校准值
  /// [id] 校准点索引 (0-3)
  /// [value] 校准值
  Future<void> setHeaterCalibration1(int id, int value) async {
    heaterCalibrations1[id] = value;
    update();

    final result =
        await deviceService.saveCalibrationValue("h2 cal${id + 1}", value);

    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
  }

  /// 执行泵校准动作
  /// 包含完整的机械臂移动和泵操作序列
  Future<bool> pumpCalibrationAction() async {
    // 1. 移动机械臂到指定位置
    bool r = await deviceService.componentAction(
        deviceService.armComponentId, deviceService.moveArm, 1 << 16 | 1);
    if (!r) {
      return false;
    }

    // 2. 抬升样本基座
    r = await deviceService.componentAction(deviceService.sampleBaseId,
        deviceService.lift, (53 * 29.62962963).toInt());
    if (!r) {
      return false;
    }

    // 3. 执行泵动作（包含管道选择和速度等级）
    r = await deviceService.componentAction(
        deviceService.waterSupportComponentId,
        deviceService.pumpAction,
        (selectedCalibrationPipeIndex + 1) << 16 |
            (selectedSpeedLevel & 0xffff));
    if (!r) {
      return false;
    }

    // 4. 机械臂归位
    r = await deviceService.componentAction(
        deviceService.armComponentId, deviceService.moveArm, 0);
    if (!r) {
      return false;
    }

    // 5. 样本基座下降
    r = await deviceService.componentAction(
        deviceService.sampleBaseId, deviceService.down, 0);
    if (!r) {
      return false;
    }

    return true;
  }

  /// 设置X轴归位校准值
  /// [value] 校准值
  Future<bool> setXarmHomeCalibrationValue(int value) async {
    final r = await deviceService.saveCalibrationValue("x home", value);
    if (!r) {
      return false;
    }
    xarmHomeCalibrationValue = value;
    update();
    return true;
  }

  /// 设置Y轴归位校准值
  /// [value] 校准值
  Future<bool> setYarmHomeCalibrationValue(int value) async {
    final r = await deviceService.saveCalibrationValue("y home", value);
    if (!r) {
      return false;
    }
    yarmHomeCalibrationValue = value;
    update();
    return true;
  }

  /// 设置泵校准值
  /// [channel] 通道编号
  /// [speed] 速度等级 (0=低速, 1=高速)
  /// [value] 校准值
  Future<bool> setPumpCalibrationValue(
      int channel, int speed, double value) async {
    return deviceService.saveCalibrationValue(
        "cl${channel + 1}_${speed == 0 ? "l" : "h"}", (value * 10).toInt());
  }

  /// 设置目标温度
  Future<bool> setTargetTemperature(int val) async {
    return deviceService.saveCalibrationValue("t temp", val);
  }

  /// 设置加速持续时间
  Future<bool> setAccDuration(int val) async {
    return deviceService.saveCalibrationValue("acc d", val);
  }

  /// 设置平衡持续时间
  Future<bool> setBalanceDuration(int val) async {
    return deviceService.saveCalibrationValue("blc d", val);
  }

  /// 设置通道清洁剂量
  Future<bool> setChannelCleanDosage(int val) async {
    final result = await deviceService.saveCalibrationValue("cln do", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    channelCleanDosage = val;
    return true;
  }

  /// 开始持续获取传感器值（带机械臂移动）
  /// [val] 参数值
  Future<bool> startGetSensorValueConinues(int val) async {
    if (_startGetSensorValue) return false;
    _startGetSensorValue = true;

    // 1. 抬升样本基座
    bool r = await deviceService.componentAction(
        deviceService.sampleBaseId, deviceService.GetSensorValuelift, val);
    if (!r) {
      return false;
    }

    // 2. Y轴移动
    r = await deviceService.componentAction(deviceService.armComponentId,
        deviceService.yMoveAction, (15 * 29.62962963).toInt());
    if (!r) {
      return false;
    }

    // 3. X轴移动到第一个测量位置
    r = await deviceService.componentAction(deviceService.armComponentId,
        deviceService.xMoveAction, ((410 - (val * 375)) * 29.62962963).toInt());
    if (!r) {
      return false;
    }

    // 4. 延迟后获取第一个传感器值（毫升检测）
    await 300.milliseconds.delay();
    detectorVal_ml = await deviceService.getSensorValue(
        deviceService.armComponentId, deviceService.distantSensorId);
    update();

    // 5. X轴移动到第二个测量位置
    r = await deviceService.componentAction(deviceService.armComponentId,
        deviceService.xMoveAction, ((380 - (val * 375)) * 29.62962963).toInt());
    if (!r) {
      return false;
    }

    // 6. 延迟后获取第二个传感器值（臂检测）
    await 300.milliseconds.delay();
    detectorVal_bra = await deviceService.getSensorValue(
        deviceService.armComponentId, deviceService.distantSensorId);
    update();

    // 7. 计算综合检测值
    detectorVal = detectorVal_bra - detectorVal_ml;

    // 8. 机械臂归位
    r = await deviceService.componentAction(
        deviceService.armComponentId, deviceService.moveArm, 0);
    if (!r) {
      return false;
    }

    // 9. 样本基座下降
    r = await deviceService.componentAction(
        deviceService.sampleBaseId, deviceService.GetSensorValuedown, val);
    if (!r) {
      return false;
    }

    update();
    return true;
  }

  /// 开始持续获取传感器值（简化版）
  /// [val] 参数值
  Future<bool> startGetSensorValueConinues1(int val) async {
    if (_startGetSensorValue) return false;
    _startGetSensorValue = true;

    // 简化版的传感器值获取流程
    bool r = await deviceService.componentAction(
        deviceService.sampleBaseId, deviceService.GetSensorValuelift, val);
    if (!r) {
      return false;
    }

    r = await deviceService.componentAction(deviceService.armComponentId,
        deviceService.yMoveAction, (15 * 29.62962963).toInt());
    if (!r) {
      return false;
    }

    r = await deviceService.componentAction(deviceService.armComponentId,
        deviceService.xMoveAction, ((410 - (val * 375)) * 29.62962963).toInt());
    if (!r) {
      return false;
    }

    await 300.milliseconds.delay();
    detectorVal = await deviceService.getSensorValue(
        deviceService.armComponentId, deviceService.distantSensorId);
    update();

    r = await deviceService.componentAction(
        deviceService.armComponentId, deviceService.moveArm, 0);
    if (!r) {
      return false;
    }

    r = await deviceService.componentAction(
        deviceService.sampleBaseId, deviceService.GetSensorValuedown, val);
    if (!r) {
      return false;
    }

    update();
    return true;
  }

  // 以下是一系列传感器校准值设置方法
  //超声波是否为负数
  bool ultrasonicNegative(int detectorVal) {
    if (detectorVal < 0) {
      showHint("超声波检测负数", HintType.DANGER);
      return true;
    }
    return false;
  }

  /// 设置距离传感器校准值1（空容器检测）
  Future<bool> setDistanceSenorCalibration1() async {
    if (ultrasonicNegative(detectorVal)) return false;
    emptyDetectValue = detectorVal;
    update();
    return await deviceService.saveCalibrationValue("empty l", detectorVal);
  }

  /// 设置距离传感器校准值2（空容器检测1）
  Future<bool> setDistanceSenorCalibration2() async {
    if (ultrasonicNegative(detectorVal)) return false;
    emptyDetectValue1 = detectorVal;
    update();
    return await deviceService.saveCalibrationValue("empty 2", detectorVal);
  }

  /// 设置距离传感器校准值3（满容器检测）
  Future<bool> setDistanceSenorCalibration3() async {
    if (ultrasonicNegative(detectorVal)) return false;
    fullDetectValue = detectorVal;
    update();
    return await deviceService.saveCalibrationValue("full 1", detectorVal);
  }

  /// 设置距离传感器校准值4（满容器检测1）
  Future<bool> setDistanceSenorCalibration4() async {
    if (ultrasonicNegative(detectorVal)) return false;
    fullDetectValue1 = detectorVal;
    update();
    return await deviceService.saveCalibrationValue("full 2", detectorVal);
  }

  /// 设置距离传感器校准值5（满容器检测2）
  Future<bool> setDistanceSenorCalibration5() async {
    if (ultrasonicNegative(detectorVal)) return false;
    fullDetectValue2 = detectorVal;
    update();
    return await deviceService.saveCalibrationValue("full 3", detectorVal);
  }

  /// 设置客户自定义传感器校准值
  Future<void> setCustomerSensorCalibration() async {
    if (ultrasonicNegative(detectorVal)) return;
    if (customerDetectValue == detectorVal) {
      stopGetSensorValue();
      return;
    }
    customerDetectValue = detectorVal;
    update();
    await deviceService.saveCalibrationValue("cust l", detectorVal);
    stopGetSensorValue();
  }

  /// 停止获取传感器值
  void stopGetSensorValue() {
    Future.microtask(() async {
      print("关闭传感器");
      await 500.milliseconds.delay();
      _startGetSensorValue = false;
    });
  }
}
